<template>
  <div class="login-form-container">
    <div class="login-title">
      账号登录
      <el-tooltip popper-class="login-tooltip" effect="dark" content="钉钉扫码登录" placement="right">
        <img :src="loginErcode" alt="" @click="$emit('tapLoginTap')">
      </el-tooltip>
    </div>

    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left" @submit.native.prevent>
      <div v-if="show" class="error">
        <svg-icon icon-class="error" class="error-icon" />
        <span>{{ message }}</span>
      </div>
      <el-form-item prop="username" class="user-name">
        <el-input v-model.trim="loginForm.username" class="font-14" name="username" type="text" auto-complete="on" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item prop="password" class="password">
        <el-input
          :type="pwdType"
          v-model="loginForm.password"
          class="font-14"
          name="password"
          auto-complete="on"
          placeholder="请输入登录密码"
          @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon v-if="pwdType" icon-class="eye" />
          <svg-icon v-else icon-class="eye-o" />
        </span>
      </el-form-item>
      <el-form-item prop="verifyCode" class="verify-code">
        <el-input
          v-model="loginForm.verifyCode"
          type="text"
          name="verifyCode"
          maxlength="4"
          class="font-14"
          auto-complete="off"
          placeholder="请输入验证码"
          @keyup.enter.native="handleLogin" />
        <span class="identify-code" @click="refreshCode(1)">
          <s-identify :identify-code="identifyCode" :font-size-min="25" :content-width="120" :content-height="48" />
        </span>
      </el-form-item>
      <div class="mb15">
        <el-checkbox v-model="checked" checked>记住用户信息</el-checkbox>
        <div class="forget-password" @click="getPwd">忘记密码？</div>
      </div>
      <el-form-item>
        <el-button :loading="loading" type="primary" style="width:100%;font-size: 14px;" @click.native.prevent="handleLogin">
          登录
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      :visible.sync="pwdDialogVisible"
      :append-to-body="true"
      width="480px"
      center
      class="pwd-dialog"
      @close="handleClose">
      <template slot="title">
        <div class="pwd-title">
          <img :src="crmLogo" class="pwd-logo-img" alt="共创平台">
        </div>
      </template>
      <send-pwd-dialog ref="sendPwd" @closeDialog="closeDialog"/>
    </el-dialog>
  </div>
</template>

<script>
import SIdentify from '@/components/Identify';
import SendPwdDialog from '@/components/SendPwdDialog';
import refreshCode from '@/mixins/refreshCode';
import { encryption, decrypt } from '@/utils';
// img
import loginErcode from '@/assets/login_ercode.png';
import crmLogo from '@/assets/crm_logo.png';

export default {
  name: 'Login',
  components: {
    SIdentify,
    SendPwdDialog
  },
  mixins: [refreshCode],
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能小于6位'));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('验证码不能小于4位'));
      } else {
        callback();
      }
    };
    return {
      crmLogo,
      loginErcode,
      loginForm: {
        username: '',
        password: '',
        verifyCode: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'change', message: '请输入用户名' }],
        password: [{ required: true, trigger: 'change', validator: validatePass }],
        verifyCode: [{ required: true, trigger: 'change', validator: validateCode }]
      },
      loading: false,
      pwdType: 'password',
      loginredirect: undefined,
      checked: true,
      identifyCode: '',
      message: '',
      show: false,
      networkStatus: true,
      pwdDialogVisible: false,
      loginType: 'tab-code' // 0-手机号登录，1-钉钉二维码登录，2-钉钉自动登录(扫码后或应用内自动登录)
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.loginredirect = route.query && route.query.loginredirect;
      },
      immediate: true
    }
  },
  mounted() {
    window.addEventListener('online', () => {
      this.networkStatus = true;
    });
    window.addEventListener('offline', () => {
      this.networkStatus = false;
    });
    const username = this.getUserName();
    const password = this.getPassword();
    if (username || password) {
      this.loginForm.username = username;
      this.loginForm.password = password;
    }
    this.refreshCode(1);
  },
  methods: {
    getUserName() {
      return localStorage.getItem('crm_UserName');
    },
    getPassword() {
      const password = localStorage.getItem('crm_Password');
      return password ? decrypt(password) : password;
    },
    saveUserName(name) {
      localStorage.setItem('crm_UserName', name);
    },
    savePassword(pwd) {
      const key = pwd ? encryption(pwd) : pwd;
      localStorage.setItem('crm_Password', key);
    },
    showPwd() {
      this.pwdType = this.pwdType === 'password' ? '' : 'password';
    },
    getPwd() { // 忘记密码
      this.pwdDialogVisible = true;
    },
    closeDialog(close) {
      this.pwdDialogVisible = close;
    },
    handleLogin() {
      const loginForm = this.loginForm;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          if (loginForm.verifyCode !== this.identifyCode) { // 判断验证码
            loginForm.verifyCode = '';
            this.refreshCode(1);
            // this.$message({
            //   message: '验证码错啦!',
            //   type: 'error'
            // });
            this.message = '验证码错啦！';
            this.show = true;
            return false;
          }

          // 判断复选框是否被勾选 勾选则调用配置cookie方法
          if (this.checked) {
            this.saveUserName(loginForm.username);
            this.savePassword(loginForm.password);
          } else {
            this.saveUserName('');
            this.savePassword('');
          }

          this.loading = true; // 开始登录
          this.$store.dispatch('Login', loginForm).then(async(data) => {
            this.loading = false;
            await this.$store.dispatch('GetInfo');
            if (this.loginredirect) {
              try {
                const params = JSON.parse(decodeURIComponent(this.loginredirect));
                this.$router.push(params);
              } catch (error) {
                this.$router.push({ path: '/' });
              }
            } else {
              this.$router.push({ path: '/' });
            }

            // this.$router.push({ path: '/' });
            // this.$router.push({ path: this.redirect || '/' });
          }, e => {
            if (e.message !== '用户名或密码错误！' && !e.message.includes('用户已禁用') && this.networkStatus) {
              this.$emit('loginError');
            }
            this.loading = false;
            this.message = e.message;
            this.show = true;
          }).catch(() => {
            this.loading = false;
          });
        } else {
          this.saveUserName('');
          this.savePassword('');
          return false;
        }
      });
    },
    handleClose() { // 点击右上角的关闭弹窗
      this.$refs.sendPwd.clearPwdForm();
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
$bg:#2d3a4b;
$light_gray:#495060;
$fontColor: #495060;
body{
  color: $fontColor;
}
/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 100%;
    width: 100%;
    input {
      background: transparent;
      border: none !important;
      -webkit-appearance: none;
      padding: 0px 35px 0px 15px;
      border: 1px solid #dddddd  !important;
      color: $light_gray;
      height: 48px;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: #fff !important;
      }
    }
  }
  .el-form-item {
    height: 48px;
    border-radius: 4px;
    color: #495060;
    margin-bottom: 20px !important;
    &:last-child {
      margin-bottom: 0px !important;
    }
    .el-form-item__error {
      padding-top: 3px;
    }
  }
  .verify-code input{
    width: calc(100% - 130px);
    border-radius: 4px;
    border: 1px solid #dddddd !important;
    height: 48px;
  }
  .el-form-item.is-success .el-input__inner {
    border-color: #dddddd;
  }
  .background-img {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: -1;
  }
  .login-title {
    margin-top: 40px;
    margin-bottom: 30px;
    font-size: 2rem;
    font-family:PingFangSC-Semibold,PingFang SC;
    font-weight:600;
    color:rgba(51,51,51,1);
    position: relative;
    img {
      width: 50px;
      height: 50px;
      position: absolute;
      right: 0;
      top: -10px;
      cursor: pointer;
    }
  }
  .forget-password {
    font-size: 14px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(64,110,255,1);
    cursor: pointer;
    display: inline-block;
  }
  .el-checkbox__label {
    color: #999 !important;
  }
}
.login-container .el-input input:-webkit-autofill {
  box-shadow: 0 0 0px 1000px #fff inset !important;
  -webkit-text-fill-color: $fontColor !important;
}
.pwd-dialog {
  .el-dialog {
    border-radius: 8px;
  }
  .pwd-title {
    padding-top: 38px;
  }
  .el-dialog__body {
    padding-bottom: 30px;
  }
  .el-input {
    width: 290px !important;
  }
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
// $bg:#2d3a4b;
$dark_gray: #acafb7;
$light_gray:#eee;
.font-14 {
  font-size: 14px;
}
.pwd-logo-img {
  width: 200px;
}
.login-form-container {
  height: 100%;
  width: 100%;
  margin-top: 20px;
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 0px;
    height: 100%;
    display: flex;
    align-items: center;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
    svg {
      width: 1em;
      height: 1em;
    }
  }
  button {
    height: 100%;
  }
  .error {
    width: 100%;
    height: 30px;
    padding: 6px 0 9px 15px;
    background-color: #ffeded;
    border-radius: 15px;
    font-size: 14px;
    color: #ff8294;
    margin-bottom: 11px;
    .error-icon {
      width: 1em;
      height: 1em;
    }
  }
  .identify-code {
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>

